package com.fitness.fitness.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.fitness.fitness.modal.user.vo.RoleOptionVO ;
import com.fitness.fitness.modal.response.ResponseEnum;
import com.fitness.fitness.modal.response.ServerResponseEntity;
import com.fitness.fitness.modal.user.entity.Role;
import com.fitness.fitness.service.IRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/role")
public class RoleController {

    private final IRoleService roleService;

    @GetMapping("/currUserRoles")
    public ServerResponseEntity<List<String>> currUserRoles(HttpServletRequest request){
        String loginId = StpUtil.getLoginIdAsString();
        String[] uidAndUname = loginId.split("_");
        Long userId = Long.parseLong(uidAndUname[0]);
        List<String> roles = roleService.getRoleList(userId);

        if(roles == null || roles.isEmpty()){
            return ServerResponseEntity.fail("R10001","没有对应的角色信息");
        }
        return ServerResponseEntity.success(ResponseEnum.OK.value(),roles);
    }

    @GetMapping("/getRoleOptions")
    public ServerResponseEntity<List<RoleOptionVO>> getRoleOptions(HttpServletRequest request){
        List<Role> roles = roleService.allRoles();

        if(roles == null || roles.isEmpty()){
            return ServerResponseEntity.fail("R10002","没有角色信息");
        }
        return ServerResponseEntity.success(ResponseEnum.OK.value(),roles.stream().map(r->{
            RoleOptionVO roleOptionVO = new RoleOptionVO();
            roleOptionVO.setLabel(r.getName());
            roleOptionVO.setValue(r.getId());
            return roleOptionVO;
        }).collect(Collectors.toList()));
    }
}
